import org.junit.Test;

import java.util.ArrayList;

import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;


public class Performance {
    @Test
    public void test1(){
        int arraySize = 32768;
        int data[] = new int[arraySize];
        int a = 0;
        int b = 0;
        Random random = new Random();
        for (int i = 0;i < arraySize; i++ ){
            data[i] = random.nextInt() % 256;
        }

        //排序对遍历的影响
        long stattime1 = System.nanoTime();
        for (int i = 0; i < 100000; ++i)
        {
            for (int j = 0;j < arraySize; j++ ){
                if (data[j] >= 128)
                    a += data[j];
            }
        }
        long endtime1 = System.nanoTime();
        System.out.println(endtime1 - stattime1);

        Arrays.sort(data);
        long stattime2 = System.nanoTime();
        for (int i = 0; i < 100000; ++i)
        {
            for (int j = 0;j < arraySize; j++ ){
                if (data[j] >= 128)
                    b += data[j];
            }
        }
        long endtime2 = System.nanoTime();
        System.out.println(endtime2 - stattime2);
    }

    //排序后遍历性能提升 CPU预测
    @Test
    public void test2(){
        int arraySize = 32768;
        int data[] = new int[arraySize];

        Random rnd = new Random(0);
        for (int c = 0; c < arraySize; ++c)
            data[c] = rnd.nextInt() % 256;

        long start = System.nanoTime();
        long sum = 0;
        for (int i = 0; i < 100000; ++i)
        {
            for (int c = 0; c < arraySize; ++c)
            {
                if (data[c] >= 128)
                    sum += data[c];
            }
        }
        System.out.println((System.nanoTime() - start) / 1000000000.0);
        System.out.println("sum = " + sum);

        Arrays.sort(data);

        long start1 = System.nanoTime();
        long sum1 = 0;
        for (int i = 0; i < 100000; ++i)
        {
            for (int c = 0; c < arraySize; ++c)
            {
                if (data[c] >= 128)
                    sum1 += data[c];
            }
        }

        System.out.println((System.nanoTime() - start1) / 1000000000.0);
        System.out.println("sum = " + sum1);
    }





    //高并发随机数生成
    @Test
    public void test3(){
       /* Random random = new Random();
        int next = random.nextInt();*/
        //ThreadLocalRandom threadLocalRandom = new ThreadLocalRandom();
        int v = ThreadLocalRandom.current().nextInt();
        System.out.println(v);
    }
}
